package com.zxkj.commonpatrol.ui;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.czy.basecommon.utils.base.BaseVmDataBindingActivity;
import com.czy.basecommon.utils.base.StateData;
import com.czy.basecommon.utils.constant.ItrackConstant;
import com.czy.basecommon.utils.language.SPUtil;
import com.czy.basecommon.utils.tools.ActivityTool;
import com.czy.basecommon.utils.tools.GsonUtil;
import com.czy.basecommon.utils.tools.SPUtils;
import com.czy.basecommon.utils.tools.TimeUtil;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.GravityEnum;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.popupwindow.popup.XUIPopup;
import com.xuexiang.xui.widget.toast.XToast;
import com.zxkj.commonpatrol.BR;
import com.zxkj.commonpatrol.R;
import com.zxkj.commonpatrol.adapt.HistoryQuestAdapt;
import com.zxkj.commonpatrol.adapt.QuestAddViewAdapt;
import com.zxkj.commonpatrol.adapt.QuestButtonAdapt;
import com.zxkj.commonpatrol.databinding.ActivityQuestDetatilBinding;
import com.zxkj.commonpatrol.model.entity.HistoryQuestEntity;
import com.zxkj.commonpatrol.model.post.PostLogInfo;
import com.zxkj.commonpatrol.model.response.DevEvtQuestPatrolHistoryResponse;
import com.zxkj.commonpatrol.model.response.LogBean;
import com.zxkj.commonpatrol.viewmodel.QuestDetailViewModel;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

public class QuestDetatilActivity extends BaseVmDataBindingActivity<ActivityQuestDetatilBinding, QuestDetailViewModel> {

    private HistoryQuestAdapt historyQuestAdapt;
    private String RouteInspectNo;
    private String PointNo;
    private String DevEvtNo;
    private String QuestsNo;//问题集编号
    private String name;
    private String QuestNo;//问题编号
    private int Type;
    private MiniLoadingDialog loadingDialog;
    private String ActNo;
    private int MyType;
    private String QuestName;
    private int Irregular;
    private QuestAddViewAdapt addViewAdapt;
    private Map<String, String> values;
    public int CapturePhoto; //是否必须拍照
    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_quest_detatil;
    }

    @Override
    public int initVariableId() {
        return BR.QuestDetailViewModel;
    }


    @Override
    protected void initUI() {

        if (getIntent().hasExtra("Type")) {
            Type = getIntent().getIntExtra("Type", 1);
        }
        if (Type==1){
            MyType=0;
        }else{
            MyType=1;
        }
        if (getIntent().hasExtra("RouteInspectNo")) {
            RouteInspectNo = getIntent().getStringExtra("RouteInspectNo");
        }
        if (getIntent().hasExtra("PointNo")) {
            PointNo = getIntent().getStringExtra("PointNo");
        }
        if (getIntent().hasExtra("DevEvtNo")) {
            DevEvtNo = getIntent().getStringExtra("DevEvtNo");
        }
        if (getIntent().hasExtra("QuestsNo")) {
            QuestsNo = getIntent().getStringExtra("QuestsNo");
        }
        if (getIntent().hasExtra("QuestNo")) {

            QuestNo = getIntent().getStringExtra("QuestNo");
        }
        if (getIntent().hasExtra("name")) {
            name = getIntent().getStringExtra("name");
        }
        if (getIntent().hasExtra("QuestName")) {
            QuestName = getIntent().getStringExtra("QuestName");
        }

        binding.recy.setLayoutManager(new LinearLayoutManager(this));
        binding.tvTitle.setText(name);
        binding.recyQuest.setLayoutManager(new LinearLayoutManager(this));

        binding.tvDesc.setText(QuestName);
        GetData();
    }

  public void  GetData(){
      loadingDialog = new MiniLoadingDialog(QuestDetatilActivity.this);
      loadingDialog.show();
      viewModel.getDevQuestPatrolHisoty(RouteInspectNo, PointNo, DevEvtNo, QuestsNo, QuestNo,MyType);
   }

    @Override
    protected void initData() {

    }

    @Override
    protected void setListener() {
        super.setListener();

        binding.qkBack.setOnClickListener(v -> {
            //發消息
            LiveEventBus.get("EventDeciveList").post("1");
            ActivityTool.getInstance().popOneActivity(this);
        });
            binding.llTips.setOnClickListener(v->{

//
            });
    }

    private void UpLoad(String ActNo, int LogResult,Map<String,String>maps) {
        long l = System.currentTimeMillis();
        String time = TimeUtil.getTime(l);
        List<PostLogInfo.QItemOptionLogLists> logLists=new ArrayList<>();
         if (maps!=null){
             for (Map.Entry<String,String> en:maps.entrySet()) {
                 PostLogInfo.QItemOptionLogLists bean=new PostLogInfo.QItemOptionLogLists();
                 bean.setLOG_OPT_NO(en.getKey());
                 bean.setLOG_OPT_Value(en.getValue());
                 logLists.add(bean);
             }

         }

        PostLogInfo logInfo = new PostLogInfo();
        logInfo.setActNo(ActNo);
        logInfo.setQItemOptionLogList(logLists);
        logInfo.setCreateUser(SPUtils.get(ItrackConstant.LOGINID, ""));
        logInfo.setUsrLogin(SPUtils.get(ItrackConstant.LOGINID, ""));
        logInfo.setDevEvtNo(DevEvtNo);
        logInfo.setLogDate(time);
        logInfo.setLogTime(time);
        if (Type == 1) {
            logInfo.setLogType(String.valueOf(0));
        } else {
            logInfo.setLogType(String.valueOf(1));
        }
        logInfo.setLogResult(String.valueOf(LogResult));
        logInfo.setPointNo(PointNo);
        logInfo.setQuestNo(QuestNo);
        logInfo.setQuestsNo(QuestsNo);
        logInfo.setRouteInspectNo(RouteInspectNo);

        viewModel.uploadLog(logInfo);
    }

    @Override
    protected void dataObserver() {
        super.dataObserver();
        LiveEventBus.get("refershQuestDeatil",Boolean.class).observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                GetData();
            }
        });


        viewModel.mData.observe(this, new Observer<StateData<DevEvtQuestPatrolHistoryResponse>>() {
            @Override
            public void onChanged(StateData<DevEvtQuestPatrolHistoryResponse> devEvtQuestPatrolHistoryResponseStateData) {

                if (devEvtQuestPatrolHistoryResponseStateData.getData().getQItemOptions()!=null){
                    if (devEvtQuestPatrolHistoryResponseStateData.getData().getQItemOptions().size()>0){
                         addViewAdapt  =new QuestAddViewAdapt(R.layout.item_mprofile_nomal,devEvtQuestPatrolHistoryResponseStateData.getData().getQItemOptions());

                        binding.recyQuest.setAdapter(addViewAdapt);

                    }
                }

                if (devEvtQuestPatrolHistoryResponseStateData.getData().getQItemActions()!=null){
                    if (devEvtQuestPatrolHistoryResponseStateData.getData().getQItemActions().size()>0){
                        int spanCount;
                        if (devEvtQuestPatrolHistoryResponseStateData.getData().getQItemActions().size()>3){
                            spanCount=3;
                        }else{

                            spanCount=devEvtQuestPatrolHistoryResponseStateData.getData().getQItemActions().size();
                        }
                        GridLayoutManager layoutManager = new GridLayoutManager(QuestDetatilActivity.this, spanCount);
                         binding.recyButton.setLayoutManager(layoutManager);
                        List<DevEvtQuestPatrolHistoryResponse.QItemAction> qItemActions = devEvtQuestPatrolHistoryResponseStateData.getData().getQItemActions();
                       
                        QuestButtonAdapt adapt =new QuestButtonAdapt(R.layout.item_button,qItemActions);

                        binding.recyButton.setAdapter(adapt);
                        adapt.setmDataCallBack(new QuestButtonAdapt.MyItemDataCallBack() {
                            @Override
                            public void onDataSuccessCallBack(Object o) {
                                Integer  position=(Integer)o;
                                Irregular=adapt.getData().get(position).Irregular;
                                if (Irregular==0){
                                    //yes
                                    new MaterialDialog.Builder(QuestDetatilActivity.this)
                                            .content("是否確認選擇?")
                                            .contentGravity(GravityEnum.CENTER)
                                            .negativeColor(getResources().getColor(R.color.colorPrimary))
                                            .positiveColor(getResources().getColor(R.color.colorPrimary))
                                            .buttonsGravity(GravityEnum.CENTER)
                                            .positiveText("是")
                                            .negativeText("否")
                                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                                @Override
                                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                            ActivityTool.getInstance().finishAllActivities();
//                          ARouter.getInstance().build("/Login/LoginActivity").navigation(getContext().getApplicationContext());
                                                    if (loadingDialog == null) {
                                                        loadingDialog = new MiniLoadingDialog(QuestDetatilActivity.this, "加載中...");
                                                    }
                                                    loadingDialog.show();
                                                    ActNo = adapt.getData().get(position).ActCode;
                                                    CapturePhoto=adapt.getData().get(position).CapturePhoto;
                                                     if (addViewAdapt!=null){
                                                        values = addViewAdapt.Values;
                                                     }else{
                                                         values=new HashMap<>();
                                                     }

                                                    //上传正常巡检记录
                                                    UpLoad(ActNo, 1,values);

                                                }
                                            }).show();
                                }else{
                                    //no
                                    new MaterialDialog.Builder(QuestDetatilActivity.this)
                                            .content("是否確認選擇?")
                                            .contentGravity(GravityEnum.CENTER)
                                            .negativeColor(getResources().getColor(R.color.colorPrimary))
                                            .positiveColor(getResources().getColor(R.color.colorPrimary))
                                            .buttonsGravity(GravityEnum.CENTER)
                                            .positiveText("是")
                                            .negativeText("否")
                                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                                @Override
                                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                            ActivityTool.getInstance().finishAllActivities();
//                          ARouter.getInstance().build("/Login/LoginActivity").navigation(getContext().getApplicationContext());
                                                    if (loadingDialog == null) {
                                                        loadingDialog = new MiniLoadingDialog(QuestDetatilActivity.this, "加載中...");
                                                    }
                                                    loadingDialog.show();
                                                    ActNo = adapt.getData().get(position).ActCode;
                                                    if (addViewAdapt!=null){
                                                        values = addViewAdapt.Values;
                                                    }else{
                                                        values=new HashMap<>();
                                                    }
                                                    CapturePhoto=adapt.getData().get(position).CapturePhoto;
                                                    //上传异常巡检记录
                                                    UpLoad(ActNo, 0,values);

                                                }
                                            }).show();
                                }
                            }

                            @Override
                            public void onDataFailCallBack(Object o, Object t1) {

                            }
                        });

            }}


            }
        });
        viewModel.mHistoryData.observe(this, new Observer<StateData<List<DevEvtQuestPatrolHistoryResponse.DevEvtQuestHis>>>() {
            @Override
            public void onChanged(StateData<List<DevEvtQuestPatrolHistoryResponse.DevEvtQuestHis>> listStateData) {
                if (loadingDialog != null) {
                    loadingDialog.dismiss();
                }
                if (listStateData.getStatus() == StateData.DataStatus.SUCCESS) {
                      if (TextUtils.isEmpty((viewModel.Tips.get()))){
                         binding.llTips.setVisibility(View.GONE);
                         binding.llDt.setVisibility(View.GONE);
                    }else{
                          binding.llTips.setVisibility(View.VISIBLE);
                          binding.llDt.setVisibility(View.GONE);
                    }

                    if (historyQuestAdapt == null) {
                        historyQuestAdapt = new HistoryQuestAdapt(R.layout.item_quest_detail_list, listStateData.getData());
                        historyQuestAdapt.setOnCallPhoneCallBack(new HistoryQuestAdapt.OnCallPhoneCallBack() {
                            @Override
                            public void onCallPhone(String number) {
                                if (!TextUtils.isEmpty(number)) {
                                    callPhone(number);
                                }

                            }
                        });
                        historyQuestAdapt.setmUnDataCallBack(new HistoryQuestAdapt.MyUnCheckPointListCallBack<String>() {
                            @Override
                            public void onDataSuccessCallBack(String o,String o1) {
                                    Bundle bundle = new Bundle();
                                    bundle.putString("LogId", o);
                                    bundle.putInt("IsUnCheck",1);
                                    String s = viewModel.Tips.get();
                                    bundle.putString("tips", s);
                                    bundle.putString("title", o1);
                                    startActivity(AddExceptionActivity.class, bundle);
                            }

                            @Override
                            public void onDataFailCallBack(String o, String t1) {

                            }
                        });
                        binding.recy.setAdapter(historyQuestAdapt);
                        historyQuestAdapt.setmDataCallBack(new HistoryQuestAdapt.MyCheckPointListCallBack<String>() {
                            @Override
                            public void onDataSuccessCallBack(String integer) {
                                loadingDialog = new MiniLoadingDialog(QuestDetatilActivity.this);
                                loadingDialog.show();
                                //去修复
                                viewModel.getFixException(integer);
                            }

                            @Override
                            public void onDataFailCallBack(String integer, String t1) {

                            }
                        });
                        historyQuestAdapt.setmJSDataCallBack(new HistoryQuestAdapt.MyJSCheckPointListCallBack<String>() {
                            @Override
                            public void onDataSuccessCallBack(String o, String t1) {
                                Bundle bundle = new Bundle();
                                bundle.putString("LogId", o);
                                bundle.putInt("IsUnCheck",1);
                                String s = viewModel.Tips.get();
                                bundle.putString("tips", s);
                                bundle.putBoolean("js",true);
                                bundle.putString("title", t1);
                                startActivity(AddExceptionActivity.class, bundle);
                            }

                            @Override
                            public void onDataFailCallBack(String o, String t1) {

                            }
                        });
                    } else {
                        historyQuestAdapt.setNewData(listStateData.getData());
                    }
                }else{
                    binding.llTips.setVisibility(View.GONE);
                    binding.llDt.setVisibility(View.GONE);
                }
            }
        });

        viewModel.FixException.observe(this, new Observer<StateData<Object>>() {
            @Override
            public void onChanged(StateData<Object> objectStateData) {
                if (loadingDialog != null) {

                    loadingDialog.dismiss();
                }
                if (objectStateData.getStatus() == StateData.DataStatus.SUCCESS) {
                    //修复成功
                   GetData();
                } else {
                    //修复失败
                    XToast.error(QuestDetatilActivity.this, "修復失敗").show();
                }
            }
        });

        viewModel.UpLoad.observe(this, new Observer<StateData<String>>() {
            @Override
            public void onChanged(StateData<String> objectStateData) {
                if (loadingDialog != null) {
                    loadingDialog.dismiss();
                }
                if (objectStateData.getStatus() == StateData.DataStatus.SUCCESS) {

                    XToast.success(QuestDetatilActivity.this, "成功").show();
                    if (Irregular == 1) {
                        Bundle bundle = new Bundle();
                        if (objectStateData.getData() == null) {
                            bundle.putString("LogId", "");
                        } else {
                            bundle.putString("LogId", objectStateData.getData());
                        }
                        String s = viewModel.Tips.get();

                        bundle.putString("tips", s);
                        bundle.putInt("CapturePhoto", CapturePhoto);
                        bundle.putInt("Irregular", Irregular);
                        startActivity(AddExceptionActivity.class, bundle);

                        //no
                        ActivityTool.getInstance().popOneActivity(QuestDetatilActivity.this);

                    } else {

                        if (CapturePhoto==1){
                            Bundle bundle = new Bundle();
                            if (objectStateData.getData() == null) {
                                bundle.putString("LogId", "");
                            } else {
                                bundle.putString("LogId", objectStateData.getData());
                            }
                            String s = viewModel.Tips.get();
                            bundle.putInt("Irregular", Irregular);
                            bundle.putString("tips", s);
                            bundle.putInt("CapturePhoto", CapturePhoto);
                            startActivity(AddExceptionActivity.class, bundle);
                        }else{
                            //發消息
                            LiveEventBus.get("EventDeciveList").post("1");
                            ActivityTool.getInstance().popOneActivity(QuestDetatilActivity.this);
                        }

                    }
                } else {
                    //修复失败
                    XToast.error(QuestDetatilActivity.this, "失敗").show();
                }
            }
        });

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        //發消息
        LiveEventBus.get("EventDeciveList").post("1");
    }

    /**
     * 拨打电话（直接拨打电话）
     * @param number 电话号码
     */

    private void callPhone(String number) {
        new MaterialDialog.Builder(this)
                .content("是否撥打"+number+"?")
                .contentGravity(GravityEnum.CENTER)
                .negativeColor(getResources().getColor(R.color.colorPrimary))
                .positiveColor(getResources().getColor(R.color.colorPrimary))
                .buttonsGravity(GravityEnum.CENTER)
                .positiveText("是")
                .negativeText("否")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                            ActivityTool.getInstance().finishAllActivities();
//                          ARouter.getInstance().build("/Login/LoginActivity").navigation(getContext().getApplicationContext());
                        Intent intent = new Intent(Intent.ACTION_CALL);
                        Uri data = Uri.parse("tel:" + number);
                        intent.setData(data);
                      startActivity(intent);

                    }
                }).show();

    }
}
